import { createRouter, createWebHashHistory } from "vue-router";
import NProgress from "nprogress";
import Layout from "@/views/layout/index.vue";
import { useLoginStore } from "@/store/login";
import system from "./module/system";

const router = createRouter({
    history: createWebHashHistory(),
    routes: [
        {
            name: 'login',
            path: '/login',
            component: () => import('@/views/login/login.vue')
        },
        {
            name: 'register',
            path: '/register',
            component: () => import('@/views/login/register.vue')
        },
        {
            name: '',
            path: '/',
            redirect: 'home',
            component: Layout,
            children: [
                {
                    name: "home",
                    path: "home",
                    component: () => import("@/views/home.vue"),
                },
                {
                    name: "tableDemo",
                    path: "tableDemo",
                    component: () => import("@/views/tableDemo/index.vue"),
                },
            ],
        },
        system,
    ],
});

//白名单

const whiteList = ['/register']
router.beforeEach((to: { fullPath: string; path: string; }, from: { fullPath: any; }, next: (arg0: { path: string; replace: boolean; } | undefined) => void) => {
    const userLogin = useLoginStore()
    NProgress.start()
    // 访问登录页，有token不能访问，没token放行
    if (to.fullPath == '/login' ) {
        if (userLogin.token){
            next(from.fullPath)
            return
        }
        next()
        return
    }
    // 白名单，直接放行
    if (whiteList.includes(to.path)) return next()
    // 没有token,重定向到登录页
    if (!userLogin.token) return next({ path: '/login', replace: true })
    next()
})

router.afterEach(() => {
    NProgress.isStarted() && NProgress.done()
})

export default router;
